package com.fuego.creditsystemcommodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.RoomInfoMapper;
import com.fuego.creditsystemcommodity.service.IRoomInfoService;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.RoomInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.example.utils.RedisConstants.ROOM_INFO_STOCK_KEY;


@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo> implements IRoomInfoService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RoomInfoMapper roomInfoMapper;

    @Override
    public Result queryRoomInfoById(Long roomId) {
        // 查询数据库
        LambdaQueryWrapper<RoomInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoomInfo::getRoomId, roomId);
        List<RoomInfo> roomInfos = roomInfoMapper.selectList(wrapper);

        // 如果数据为空，返回错误
        if (roomInfos == null || roomInfos.isEmpty()) {
            return Result.fail("未找到房间信息");
        }

        // 缓存到 Redis，设置 1 小时过期时间
        for (RoomInfo roomInfo : roomInfos) {
            String key = ROOM_INFO_STOCK_KEY + roomInfo.getRoomId() + ":" + roomInfo.getCheckinDate();
            stringRedisTemplate.opsForValue().set(key, roomInfo.getStock().toString(), 1, TimeUnit.HOURS);
        }

        // 返回结果
        return Result.ok(roomInfos);
    }
}
